import { IBreadcrumb } from '@/base-ui/breadcrumb/types'
import { RouteRecordRaw } from 'vue-router'

export function mapMenusToRoutes(userMenus: any[]): RouteRecordRaw[] {
  const routes: RouteRecordRaw[] = []

  // 1.先加载默认所有的routes
  const allRoutes: RouteRecordRaw[] = []
  // webpack中的方法，加载所有的 ts文件, 第二个参数表示递归查找
  const routeFiles = require.context('../router/main', true, /\.ts/)

  routeFiles.keys().forEach((key) => {
    const route = require('../router/main' + key.split('.')[1])
    allRoutes.push(route.default)
  })

  // 2.再根据菜单获取需要的routes
  const _recurseGetRoute = (menus: any[]) => {
    for (const menu of menus) {
      if (menu.type === 2) {
        const route = allRoutes.find((route) => {
          return route.path === menu.url
        })
        if (route) routes.push(route)
      } else {
        _recurseGetRoute(menu.children)
      }
    }
  }

  _recurseGetRoute(userMenus)

  return routes
}

export function pathMapBreadcrumb(userMenus: any[], currentPath: string): any {
  const breadcrumb: IBreadcrumb[] = []

  for (const menus of userMenus) {
    if (menus.type === 1) {
      const childrenMenu = pathMapBreadcrumb(menus.children ?? [], currentPath)
      if (childrenMenu) {
        breadcrumb.push({
          name: menus.name,
          path: ''
        })
        breadcrumb.push({
          name: childrenMenu.name,
          path: childrenMenu.url
        })
        return breadcrumb
      }
    } else if (menus.type === 2 && menus.url === currentPath) {
      return menus
    }
  }

  // return breadcrumb
}
